package org.schat;

import org.schat.utils.UUIDUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * @Description 服务端请求分发线程
 * @Author lsh
 **/
public class SocketAcceptRunnable implements Runnable{
	private ServerSocket serverSocket;
	
	public SocketAcceptRunnable(ServerSocket serverSocket) {
		this.serverSocket=serverSocket;
	}

	@Override
	public void run() {
		Socket socket = null;
		try {
			//接收socket连接
			while ((socket = serverSocket.accept()) != null) {
                String clientId = UUIDUtils.getUUID();
				String clientName = SandSculptureName.generator();
				ClientDomain clientDoamin = IMServer.clientMap.get(clientId);
				if (clientDoamin == null) {
					clientDoamin = new ClientDomain(clientId,clientName, socket, 1,System.currentTimeMillis());
                    clientDoamin.setIp(socket.getInetAddress().getHostAddress());
                    clientDoamin.setPort(socket.getPort()+"");
					String msg=clientName+" 加入沙雕聊天室！";
					IMServer.msgQue.offer(new MessageDomain("1",msg));
					System.out.println(msg);
					IMServer.clientMap.put(clientId, clientDoamin);
				}
				//分发请求
				IMServer.executors.execute(new SocketHandlerRunnable(clientId));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
		    if(socket !=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}

}
